import api from '../../utils/api.js'

Page({
  data: {
    announcement: null,
    loading: true,
    id: null
  },

  onLoad(options) {
    const { id } = options
    if (id) {
      this.setData({ id })
      this.loadAnnouncementDetail(id)
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载公告详情
  async loadAnnouncementDetail(id) {
    try {
      this.setData({ loading: true })
      const announcement = await api.announcements.getDetail(id)
      this.setData({ 
        announcement,
        loading: false 
      })
      
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: announcement.title.length > 10 ? 
          announcement.title.substring(0, 10) + '...' : 
          announcement.title
      })
    } catch (error) {
      console.error('获取公告详情失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 点赞/取消点赞
  async onToggleLike() {
    try {
      const result = await api.announcements.toggleLike(this.data.id)
      
      // 更新本地数据
      this.setData({
        'announcement.is_liked': result.is_liked,
        'announcement.like_count': result.like_count
      })
      
      wx.showToast({
        title: result.is_liked ? '点赞成功' : '取消点赞',
        icon: 'success'
      })
    } catch (error) {
      console.error('点赞操作失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 图片预览
  onImagePreview(e) {
    const url = e.currentTarget.dataset.url
    const urls = [url]
    
    // 如果有多张图片，添加到预览列表
    if (this.data.announcement.images) {
      this.data.announcement.images.forEach(img => {
        if (img !== url && !urls.includes(img)) {
          urls.push(img)
        }
      })
    }
    
    wx.previewImage({
      current: url,
      urls: urls
    })
  },

  // 点击相关公告
  onRelatedTap(e) {
    const id = e.currentTarget.dataset.id
    wx.redirectTo({
      url: `/pages/announcements/detail?id=${id}`
    })
  },

  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadAnnouncementDetail(this.data.id)
    wx.stopPullDownRefresh()
  },

  // 分享
  onShareAppMessage() {
    const announcement = this.data.announcement
    return {
      title: announcement ? announcement.title : '展馆公告',
      path: `/pages/announcements/detail?id=${this.data.id}`,
      imageUrl: announcement ? announcement.cover_image : ''
    }
  }
})